<?php

namespace App\Clients;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Message\ResponseInterface;

class BaseClient
{
    protected Client $client;

    protected int $timeout = 30;

    public function __construct()
    {
        $this->client = new Client([
            "verify"=>false,
            "http_errors"=>false,
            "timeout"=>$this->timeout,
        ]);
    }

    /**
     * @throws GuzzleException
     */
    protected function postData($url, $data, $headers, $params="json", $other = []): ResponseInterface
    {
        $extend = [
            //"headers"=>$headers,
        ];
        !empty($headers) and $extend["headers"] = $headers;
        switch($params){
            case "json":
                $extend["json"] = $data;
                break;
            case "form":
                $extend["form_params"] = $data;
                break;
            case "body":
                $extend["headers"]["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
                //content-type
                $extend["body"] = $data;
                break;
        }
        !empty($other) and $extend = array_merge($extend,$other);
//        var_dump($extend);
//        exit();
        return $this->client->post($url,$extend);
    }

    /**
     * @throws GuzzleException
     */
    protected function getData($url, $data, $headers, $other = []): ResponseInterface
    {
        $extend = [
            "headers"=>$headers,
        ];
        $url .= "?".http_build_query($data);
        !empty($other) and $extend = array_merge($extend,$other);
        return $this->client->get($url,$extend);
    }

}
